package cz.cvut.fit.sin.eventlocator.core;

import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.web.util.UriUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import cz.cvut.fit.sin.eventlocator.data.Location;

/**
 * Get GPS coordinates from address
 * 
 */
public class PlaceFinder {

	private static final String BASE_URL = "http://where.yahooapis.com/geocode?location=";

	public Location getLocation(String address) throws Exception {
		String url = UriUtils.encodeHttpUrl(BASE_URL + address, "UTF-8");
		return getLocation(new URL(url).openStream());
	}

	private Location getLocation(InputStream is) throws Exception {
		DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document document = documentBuilder.parse(is);
		NodeList list = document.getElementsByTagName("Result");
		if (list.getLength() > 0) {
			double latitude = Double.parseDouble(document.getElementsByTagName("latitude").item(0).getTextContent());
			double longitude = Double.parseDouble(document.getElementsByTagName("longitude").item(0).getTextContent());
			return new Location(latitude, longitude);
		}
		return null;
	}

}
